<template>
  <basic-container>
    <el-form :inline="true" :model="query" class="demo-form-inline">
      <el-row>
        <el-form-item label="项目编号:">
          <el-input v-model="query.projectCode" clearable placeholder="项目编号" size="small"></el-input>
        </el-form-item>
        <el-form-item label="取证单编号:">
          <el-input v-model="query.code" clearable placeholder="取证单编号" size="small"></el-input>
        </el-form-item>
        <el-form-item label="项目名称:">
          <el-input v-model="query.projectName" clearable placeholder="项目名称" size="small"></el-input>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item>
          <el-button size="small" type="primary" icon="el-icon-search" @click="onSearch" :loading="loading">搜索
          </el-button>
          <el-button size="small" icon="el-icon-delete" @click="searchReset" :loading="loading">清空</el-button>
        </el-form-item>
      </el-row>
    </el-form>
    <div class="btn-operate">
      <el-button v-if="permissions.auditevidence_add" @click="createEvidence" type="primary" size="small" icon="el-icon-plus">
        审计取证单
      </el-button>
    </div>
    <el-table
      v-loading="loading"
      ref="table"
      :data="tableData"
      border
      highlight-current-row
      :row-key="rowKeyMethod"
      style="width: 100%"
      class="current-page"
      @row-click="handleRowClick">
      <el-table-column type="expand" width="1">
        <template slot-scope="props">
          <el-table
            :data="props.row.auditEvidences"
            style="width: 100%"
            @cell-click="handleCellClick"
            :row-key="rowKeyMethod1"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="code" label="取证单编号" width="150">
            </el-table-column>
            <el-table-column prop="pointCode" label="疑点编号" width="150">
            </el-table-column>
            <el-table-column prop="pointDesc" label="疑点描述">
            </el-table-column>
            <el-table-column prop="status" label="取证单状态">
              <template slot-scope="scope">
                <span v-if="scope.row.status === 0 || scope.row.status === null">新建</span>
                <span v-else-if="scope.row.status === 1">审核中</span>
                <span v-else-if="scope.row.status === 2">驳回</span>
                <span v-else-if="scope.row.status === 8">审批通过待发送</span>
                <span v-else-if="scope.row.status === 3">待答复</span>
                <span v-else-if="scope.row.status === 4">已答复待转交审计组</span>
                <span v-else-if="scope.row.status === 5">已转交审计组</span>
                <span v-else-if="scope.row.status === 6">已生成问题</span>
                <span v-else-if="scope.row.status === 7">已关闭</span>
                <span v-else>未知状态</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="170">
              <template slot-scope="scope">
                <el-button v-if="permissions.auditevidence_get" type="text" size="small" icon="el-icon-view" @click="showViewBox(scope.row)">查看</el-button>
                <el-button v-if="permissions.auditevidence_add && (scope.row.status < 3 && scope.row.status !== 1)" type="text" size="small" icon="el-icon-edit" @click="showEditBox(scope.row)">编辑</el-button>
                <el-button v-if="permissions.auditevidence_send && scope.row.status === 8" type="text" size="small" icon="el-icon-edit" @click="showSendBox(scope.row)">发送</el-button>
                <el-button v-if="userInfo.userId === scope.row.receiverId && scope.row.status === 3" type="text" size="small" icon="el-icon-edit" @click="showReplyBox(scope.row)">答复</el-button>
                <el-button v-if="permissions.auditenvidence_examine && scope.row.status === 4" type="text" size="small" icon="el-icon-edit" @click="showAuditBox(scope.row)">审核</el-button>
                <el-button v-if="permissions.create_dicovery && scope.row.status === 5" type="text" size="small" icon="el-icon-edit" @click="showConfirmBox(scope.row)">确认问题</el-button>
                <el-button v-if="scope.row.taskId" type="text" size="small" icon="el-icon-edit" @click="showTaskAuditTaskDialog(scope.row)">审批</el-button>
                <el-button v-if="scope.row.status > 0 && (roles[0] !== '1728294507357310977') " type="text" size="small" icon="el-icon-view" @click="showTaskAuditLogDialog(scope.row)">审批日志</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="项目编号" prop="projectCode">
      </el-table-column>
      <el-table-column prop="projectName" label="项目名称">
      </el-table-column>
      <el-table-column prop="evidenceCount" label="取证单数量">
      </el-table-column>
      <el-table-column prop="noSubmitCount" label="未提交审批">
      </el-table-column>
      <el-table-column prop="auditingCount" label="审批中">
      </el-table-column>
      <el-table-column prop="replyCount" label="待答复">
      </el-table-column>
      <el-table-column prop="reviewCount" label="已答复待审核">
      </el-table-column>
      <el-table-column prop="processCount" label="待处理">
      </el-table-column>
      <el-table-column prop="problemCount" label="已生成问题">
      </el-table-column>
      <el-table-column prop="endCount" label="已关闭">
      </el-table-column>
      <el-table-column label="操作" width="170">
        <template slot-scope="scope">
          <el-button v-if="permissions.evidence_submit && scope.row.noSubmitCount > 0" type="text" size="small" icon="el-icon-edit" @click="submitApproval(scope.row)">提交</el-button>
          <el-button v-if="permissions.evidence_audit  && scope.row.auditingCount > 0" type="text" size="small" icon="el-icon-edit" @click="approvalThrough(scope.row)">通过</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 30, 40 ,50 ,100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total">
      </el-pagination>
    </div>

    <el-dialog title="审计取证单" fullscreen custom-class="ledger" :visible.sync="formBox" :close-on-click-modal="!formBox" :append-to-body="true" :before-close="resetForm" width="1200px" top="5vh">
      <div class="title">基本信息</div>
      <el-form ref="optForm" :model="form" label-width="90px">
        <el-row>
          <el-col :span="6">
            <el-form-item label-width="100px" label="项目名称:" prop="projectName">
              <el-input v-model="form.projectName" placeholder="项目名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="100px" label="疑点编号: " prop="pointCode" >
              <el-input v-model="form.pointCode" placeholder="选择疑点编号" @focus="showChoseDoubtful()" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label-width="100px"  label="疑点描述:" prop="pointDesc">
              <el-input v-model="form.pointDesc" :autosize="{ minRows: 2}" type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="title">基本信息</div>
      <el-form ref="optForm" :model="form" label-width="90px">
        <el-row>
          <el-col>
            <el-form-item label-width="100px" label="审计事项:" prop="auditMatter">
              <el-input v-model="form.auditMatter" placeholder="审计事项" type="textarea" autosize :disabled="isEdit || (form.status >= 3 || form.status === 1)"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label-width="100px" label="审计事项摘要:" prop="auditPurpose">
              <el-input v-model="form.auditMatterAbstract" placeholder="审计事项摘要" type="textarea" autosize :disabled="isEdit || (form.status >= 3 || form.status === 1)"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label-width="100px" label="定性及依据:" prop="lawId">
              <el-input v-model="form.lawContent" type="textarea" placeholder="定性及依据" autosize style="width: 90%;"></el-input>
              <el-button @click="openLawFunction" type="primary" size="small">选择法律法规</el-button>
            </el-form-item>
          </el-col>
        </el-row>
<!--        <div class="title">审计取证单文书</div>
        <el-row >
          <el-col :span="24">
            <el-form-item label-width="110px" label="审计取证单:" prop="projectName">
              <web-document :form-data="form" readWord="edit" :pageType="'evidence'" @createWordFile="wordFileHandle" />
            </el-form-item>
          </el-col>
        </el-row>-->
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm" size="small" icon="el-icon-close">关闭</el-button>
        <el-button v-if="!isView" type="primary" @click="submit" size="small" icon="el-icon-check" :loading="loading">保存</el-button>
        <el-button v-if="!isView && (!form.status || form.status === 0 || form.status === 2)" type="primary" @click="submitAudit" size="small" icon="el-icon-check" :loading="loading">保存送审</el-button>

      </span>
      <table-law :dialog="TableLawVisible" ref="dataLaw" @cancelDialog="closeLawDialog"></table-law>
    </el-dialog>


    <el-dialog title="审计取证单-发送" fullscreen custom-class="ledger" :visible.sync="sendBox" :close-on-click-modal="!sendBox" :append-to-body="true" :before-close="resetForm" width="1200px" top="5vh">
      <div class="title">基本信息</div>
      <el-form ref="optForm" :model="form" label-width="90px">
        <el-row>
          <el-col :span="6">
            <el-form-item label-width="100px" label="项目名称:" prop="projectName">
              <el-input v-model="form.projectName" placeholder="项目名称" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="100px" label="疑点编号: " prop="pointCode" >
              <el-input v-model="form.pointCode" placeholder="选择疑点编号" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="100px" label="接收人: " prop="pointCode" >
              <el-input v-model="form.receiver" placeholder="选择接收人" @focus="showTransferDialog(['receiverId','receiver'], 'auditedUser', false)" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label-width="100px" label="疑点描述:" prop="pointDesc">
              <el-input v-model="form.pointDesc" :autosize="{ minRows: 2}" type="textarea" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="title">基本信息</div>
      <el-form ref="optForm" :model="form" label-width="90px">
        <el-row>
          <el-col>
            <el-form-item label-width="100px" label="审计事项:" prop="auditMatter">
              <el-input v-model="form.auditMatter" placeholder="审计事项" type="textarea" autosize :readonly="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label-width="100px" label="审计事项摘要:" prop="auditPurpose">
              <el-input v-model="form.auditMatterAbstract" placeholder="审计事项摘要" type="textarea" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label-width="100px" label="定性及依据:" prop="lawId">
              <el-input v-model="form.lawContent" type="textarea" placeholder="定性及依据" autosize style="width: 90%;" :readonly="true"></el-input>
<!--              <el-button @click="openLawFunction" type="primary" size="small">选择法律法规</el-button>-->
            </el-form-item>
          </el-col>
        </el-row>
<!--        <div class="title">审计取证单文书</div>
        <el-row >
          <el-col :span="24">
            <el-form-item label-width="110px" label="审计取证单:" prop="projectName">
              <web-document :form-data="form" readWord="edit" :pageType="'evidence'" @createWordFile="wordFileHandle" />
            </el-form-item>
          </el-col>
        </el-row>-->
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm" size="small" icon="el-icon-close">关闭</el-button>
        <el-button v-if="!isView" type="primary" @click="sendEvidence" size="small" icon="el-icon-check" :loading="loading">发送</el-button>
      </span>
    </el-dialog>

    <el-dialog title="审计取证单-答复" fullscreen custom-class="ledger" :visible.sync="replyBox" :close-on-click-modal="!replyBox" :append-to-body="true" :before-close="resetForm" width="1200px" top="5vh">
      <div class="title">基本信息</div>
      <el-form ref="optForm" :model="form" label-width="90px">
        <el-row>
          <el-col :span="6">
            <el-form-item label-width="100px" label="项目名称:" prop="projectName">
              {{form.projectName}}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="140px" label="疑点编号: " prop="pointCode" >
              {{form.pointCode}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label-width="140px" label="疑点描述:" prop="pointDesc">
              {{form.pointDesc}}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="title">基本信息</div>
      <el-form ref="optForm" :model="form" label-width="90px">
        <el-row>
          <el-col>
            <el-form-item label-width="140px" label="审计事项:" prop="auditMatter">
              <pre class="pre-style">{{ form.auditMatter }}</pre>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label-width="140px" label="审计事项摘要:" prop="auditPurpose">
              <pre class="pre-style">{{ form.auditMatterAbstract }}</pre>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="140px" label="定性及依据:" prop="lawId">
              <pre class="pre-style">{{ form.lawContent }}</pre>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">被审计单位答复</div>
        <el-row>
          <el-col>
            <el-form-item label-width="140px" label="证据提供单位意见:" prop="auditPurpose">
              <el-input v-model="form.providerOpinion" placeholder="证据提供单位意见" type="textarea"></el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label-width="140px" label="附件:">
              <el-upload
                class="upload-demo"
                action="/admin/sys-file/upload"
                :headers="{Authorization}"
                :file-list="fileList"
                :on-success="handleSuccess"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :show-file-list="true">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">审计取证单文书</div>
        <el-row >
          <el-col :span="24">
            <el-form-item label-width="140px" label="审计取证单:" prop="projectName">
              <web-document :form-data="form" readWord="edit" :pageType="'evidence'" @createWordFile="wordFileHandle" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm" size="small" icon="el-icon-close">关闭</el-button>
        <el-button v-if="!isView && form.status === 3" type="primary" @click="saveSubmit" size="small" icon="el-icon-check" :loading="loading">送审</el-button>
      </span>
    </el-dialog>

    <el-dialog title="审计取证单-审核" fullscreen custom-class="ledger" :visible.sync="auditBox" :close-on-click-modal="!auditBox" :append-to-body="true" :before-close="resetForm" width="1200px" top="5vh">
      <div class="title">基本信息</div>
      <el-form ref="optForm" :model="form" label-width="90px">
        <el-row>
          <el-col :span="6">
            <el-form-item label-width="100px" label="项目名称:" prop="projectName">
              {{form.projectName}}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="140px" label="疑点编号: " prop="pointCode" >
              {{form.pointCode}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label-width="140px"  label="疑点描述:" prop="pointDesc">
              <pre class="pre-style">{{ form.pointDesc }}</pre>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="title">基本信息</div>
      <el-form ref="optForm" :model="form" label-width="90px">
        <el-row>
          <el-col>
            <el-form-item label-width="140px" label="审计事项:" prop="auditMatter">
              <pre class="pre-style">{{ form.auditMatter }}</pre>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label-width="140px" label="审计事项摘要:" prop="auditPurpose">
              <pre class="pre-style">{{ form.auditMatterAbstract }}</pre>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="140px" label="定性及依据:" prop="lawId">
              <pre class="pre-style">{{ form.lawContent }}</pre>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">被审计单位答复</div>
        <el-row>
          <el-col>
            <el-form-item label-width="140px" label="证据提供单位意见:" prop="auditPurpose">
              <pre class="pre-style">{{ form.providerOpinion }}</pre>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label-width="140px" label="附件:">
              <el-upload
                class="upload-demo"
                action="/admin/sys-file/upload"
                :headers="{Authorization}"
                :file-list="fileList"
                :on-preview="handlePreview"
                :show-file-list="true">
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">审计取证单文书</div>
        <el-row >
          <el-col :span="24">
            <el-form-item label-width="140px" label="审计取证单:">
              <web-document :form-data="form" readWord="edit" :pageType="'evidence'" @createWordFile="wordFileHandle" />
            </el-form-item>
          </el-col>
        </el-row>
<!--        <div class="title">对答复的意见和建议</div>-->
<!--        <el-row>-->
<!--          <el-col>-->
<!--            <el-form-item label-width="140px" label="意见和建议:" prop="suggestion">-->
<!--              <el-input v-model="form.suggestion" placeholder="审计组长填写意见和建议" type="textarea"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm" size="small" icon="el-icon-close">关闭</el-button>
        <el-button v-if="form.status === 4" type="primary" @click="forward" size="small" icon="el-icon-check" :loading="loading">保存并转交审计组</el-button>
      </span>
    </el-dialog>

    <el-dialog title="审计取证单-确认问题" fullscreen custom-class="ledger" :visible.sync="confirmBox" :close-on-click-modal="!confirmBox" :append-to-body="true" :before-close="resetForm" width="1200px" top="5vh">
      <div class="title">基本信息</div>
      <el-form ref="optForm" :model="form" label-width="90px">
        <el-row>
          <el-col :span="6">
            <el-form-item label-width="140px" label="项目名称:" prop="projectName">
              {{form.projectName}}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="140px" label="疑点编号:" prop="pointCode" >
              {{form.pointCode}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label-width="140px" label="疑点描述:" prop="pointDesc">
              <pre class="pre-style">{{ form.pointDesc }}</pre>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="title">基本信息</div>
      <el-form ref="optForm" :model="form" label-width="90px">
        <el-row>
          <el-col>
            <el-form-item label-width="140px" label="审计事项:" prop="auditMatter">
              <pre class="pre-style">{{ form.auditMatter }}</pre>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label-width="140px" label="审计事项摘要:" prop="auditPurpose">
              <pre class="pre-style">{{ form.auditMatterAbstract }}</pre>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="140px" label="定性及依据:" prop="lawId">
              <pre class="pre-style">{{ form.lawContent }}</pre>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">被审计单位答复</div>
        <el-row>
          <el-col>
            <el-form-item label-width="140px" label="证据提供单位意见:" prop="auditPurpose">
              <pre class="pre-style">{{ form.providerOpinion }}</pre>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label-width="140px" label="附件:">
              <el-upload
                class="upload-demo"
                action="/admin/sys-file/upload"
                :headers="{Authorization}"
                :file-list="fileList"
                :on-preview="handlePreview"
                :show-file-list="true">
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">审计取证单文书</div>
        <el-row >
          <el-col :span="24">
            <el-form-item label-width="140px" label="审计取证单:">
              <web-document :form-data="form" readWord="view" :pageType="'evidence'" @createWordFile="wordFileHandle" />
            </el-form-item>
          </el-col>
        </el-row>
<!--        <div class="title">对答复的意见和建议</div>-->
<!--        <el-row>-->
<!--          <el-col>-->
<!--            <el-form-item label-width="140px" label="意见和建议:" prop="suggestion">-->
<!--              <pre class="pre-style">{{ form.suggestion }}</pre>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm" size="small" icon="el-icon-close">关闭</el-button>
        <el-button v-if="form.status === 5" type="primary" @click="handleCloseEvidence()" size="small" icon="el-icon-check" :loading="loading">关闭疑点</el-button>
        <el-button v-if="form.status === 5" type="primary" @click="createDiscover(form)" size="small" icon="el-icon-check" :loading="loading">生成问题</el-button>
      </span>
    </el-dialog>

    <el-dialog top="5vh" :title="formTitle" :visible.sync="viewBox"
               :append-to-body="true" :before-close="closeViewBox" width="1200px">
      <AuditEvidenceView :params="form"></AuditEvidenceView>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeViewBox" size="small" icon="el-icon-close">关闭</el-button>
      </span>
    </el-dialog>

    <TaskAuditDialog :dialog="taskAuditDialog" @setValue="setTaskAuditTaskDialog" @closeDialog="closeTaskAuditTaskDialog" ref="taskAuditDialog" />
    <TaskAuditLogDialog :dialog="taskAuditLogDialog" :process-id="processId" @closeDialog="closeTaskAuditTaskLogDialog"/>
    <ChoseDoubtful :choseDoubtful="choseDoubtful" @setValue="setChoseDoubtful" @closeDialog="closeChoseDoubtful" ref="choseDoubtful" />
    <table-form ref="dataForm" @cancelDialog="closeDoubtfulDialog"></table-form>
    <EvidenceForm :evidenceDialog="evidenceDialog" @cancelDialog="closeEvidenceDialog" @setValue="evidenceDataHandle" ref="addEvidence"/>
    <FormTransfer :transferDialog="transferDialog" :transferDialogType="transferDialogType" :multiple="transferDialogMultiple" :transferCurrent="transferCurrent" @transferData="transferDataHandle" @closeTransfer="closeTransfer"/>
  </basic-container>
</template>

<script>
import {submitAudit, submit, saveSubmit, forward, getEvidence, closeEvidence, submitApproval, approvalThrough, fetchProjectList, listEvidencesByProjectId, sendEvidence} from "@/api/adis/execute/evidence";
import {delObj} from "@/api/admin/file";
import {mapGetters} from "vuex";
import Tinymce from "@/components/Tinymce/index.vue";
import TaskAuditDialog from "@/components/act/TaskAuditDialog";
import TaskAuditLogDialog from "@/components/act/TaskAuditLogDialog";
import ChoseDoubtful from "@/components/audited/ChoseDoubtful";
import TableForm from "@/components/form/projectProblem.vue";
import WebDocument from '@/components/form/webDocument.vue';
import AuditEvidenceView from "@/components/actForm/AuditEvidenceView";
import TableLaw from "@/components/table/lawList.vue";
import EvidenceForm from "@/components/form/evidenceForm.vue";
import FormTransfer from "@/components/form/transfer.vue";


export default {
  components: {
    FormTransfer,
    EvidenceForm,
    AuditEvidenceView,
    TableForm,
    ChoseDoubtful,
    Tinymce,
    TaskAuditDialog,
    TaskAuditLogDialog,
    WebDocument,
    TableLaw
  },
  data() {
    return {
      formTitle: '',
      formBox: false,
      sendBox: false,
      isEdit: false,
      isView: false,
      tableData: [],
      loading: false,
      query: {},
      form:{},
      fileForm: {},
      pointForm:{},
      fileList:[],
      newTableData:[],
      selectedRows:{
        key:'',
        value:[]
      },
      page:{
        total: 10,
        currentPage: 1
      },
      Authorization: '',
      taskAuditDialog: false,
      taskAuditLogDialog: false,
      processId : '',
      choseDoubtful: false,
      formDisplay: false,
      replyBox: false,
      auditBox: false,
      confirmBox: false,
      viewBox: false,
      TableLawVisible: false,
      evidenceDialog: false,
      transferDialog: false,
      transferDialogType: '',
      transferDialogTypeArr: [],
      transferDialogMultiple: false,
      transferCurrent: {},
    }
  },
  computed: {
    ...mapGetters(["permissions","userInfo","roles"])
  },
  created() {
    this.onLoad(this.page);
    this.Authorization = 'Bearer ' + this.$store.getters.access_token
  },
  methods: {
    evidenceDataHandle(data){
    },
    closeEvidenceDialog() {
      this.onLoad(this.page);
    },
    handleRowClick(row, event) {
      this.query.projectId = row.projectId;

      listEvidencesByProjectId(this.query).then(res => {
        this.$set(row, 'auditEvidences', res.data.data);
        // 使用$refs调用toggleRowExpansion方法，但 Element UI 默认支持点击展开，此处可省略
        this.$refs.table.toggleRowExpansion(row,true);
        // this.$set(this, "expandedRow", row);
        this.tableData.forEach(item => {
          if (item !== row) {
            this.$refs.table.toggleRowExpansion(item,false);
          }
        })
      })
    },
    rowKeyMethod(row) {
      // 使用唯一的 id 字段作为 row-key
      return row.projectId;
    },
    rowKeyMethod1(row) {
      // 使用唯一的 id 字段作为 row-key
      return row.evidenceId;
    },
    handleCellClick(row, column) {
      if (row && column.label !== "操作"){
        this.showViewBox(row)
      }
    },

    createDiscover(row){
      this.$nextTick(() => {
        this.$refs.dataForm.init(row);
      })
      setTimeout(() => {
        this.confirmBox = false;
      }, 500)
    },
    closeDoubtfulDialog(){
      this.onLoad(this.page);
    },
    /**
     * 文件上传
     */
    handleSuccess(response, file, fileList){
      console.info(response);
      if (!this.fileList) {
        this.fileList = [{url: response.data.url, name: response.data.fileName}]
      } else {
        this.fileList.push({url: response.data.url, name: response.data.fileName})
      }
    },
    handleRemove(file, fileList) {
      this.fileList.forEach((item, v) => {
        if (file.url === item.url) this.fileList.splice(v, 1)
      })
    },
    handlePreview(file) {
      const a = document.createElement('a');
      let url = file.url ? file.url : file.response.data.url;
      console.log(url);      // let fileName = '你想要的文件名.docx'; // 这里设置你想要的文件名，包括扩展名
      a.setAttribute('download', file.name);
      a.setAttribute('href', url);
      a.click();
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(index) {
      let splice = this.fileList.splice(index, 1);
      delObj(splice[0].id).then(()=>{
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      })
      // return this.$confirm(`确定移除 ${ file.fileName }？`);
    },

    showChoseDoubtful(){
      this.$nextTick(() => {
        this.$refs.choseDoubtful.initParams({
          isCreateEvidence: true,//用来创建取证单
          });
      })
    },
    closeChoseDoubtful(val){
      this.choseDoubtful= false;
    },
    setChoseDoubtful(data){
      this.choseDoubtful= false;
      // this.pointForm = data;
      this.form = data;
      this.form.auditMatter = data.keynoteTitle;
      console.log(this.form);
    },
    onSearch() {
      this.page.current = 1;
      this.onLoad(this.page);
    },
    searchReset() {
      this.query = {};
      this.page.current = 1;
      this.onLoad(this.page);
    },
    currentChange(current) {
      this.page.current = current;
      this.onLoad(this.page);
    },
    sizeChange(size) {
      this.page.size = size;
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      console.log(this.userInfo);
      this.loading = true;
      // if(this.query.publishDates) {
      //   this.query.startDate = this.query.publishDates[0];
      //   this.query.endDate = this.query.publishDates[1];
      // }
      this.query.isEngineering = 0;
      fetchProjectList(Object.assign(params, this.query, page)).then(res => {
        this.loading = false;
        const data = res.data.data;
        this.page.total = data.total;
        this.tableData = data.records;
        this.handleRowClick(this.tableData[0])
      }, () => {
        this.loading = false;
      });
    },
    showViewBox(row){
      getEvidence(row.evidenceId).then((res) => {
        this.form = res.data.data;
        this.viewBox = true;
        this.isView = true;
      });
    },
    closeViewBox() {
      this.viewBox = false;
    },

    showEditBox(row) {
      getEvidence(row.evidenceId).then((res) => {
        this.form = res.data.data;
        this.fileList = this.form.attachments;
        this.fileList.forEach((item) =>{
          item.name = item.fileName;
        })
        this.formTitle = '编辑';
        this.formBox = true;
        this.isView = false;
        this.isEdit = false;
      });
    },
    showSendBox(row) {
      getEvidence(row.evidenceId).then((res) => {
        this.form = res.data.data;
        if (this.form.receiverId === null){
          this.form.receiverId = this.form.auditedCompanyUserId;
          this.form.receiver = this.form.auditedCompanyUserName;
        }
        console.log(this.form);
        this.formTitle = '编辑';
        this.sendBox = true;
        this.isView = false;
        this.isEdit = false;
      });
    },
    resetForm() {
      this.formBox = false;
      this.sendBox = false;
      this.viewBox = false;
      this.replyBox = false;
      this.auditBox = false;
      this.confirmBox = false;
      this.isEdit = false;
      this.isView = false;
      this.form = {};
      this.pointForm = {};
      this.formTitle = '';
      this.$refs['optForm'] && this.$refs['optForm'].resetFields();
      this.fileList = [];
      this.fileForm = {};

      this.onLoad(this.page);
    },
    createEvidence() {
      this.$nextTick(() => {
        this.$refs.addEvidence.init()
      })
    },
    saveSubmit(){
      this.$refs['optForm'].validate((valid) => {
        if (valid) {
          this.form.attachments = [];
          this.fileList.forEach(file => {
            this.form.attachments.push({fileName: file.name, fileUrl: file.url})
          })
          this.loading = true;
          saveSubmit(this.form).then((res) => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.resetForm();
            this.onLoad(this.page);
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    submit() {
      this.$refs['optForm'].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.fileList.forEach(file => {
            this.form.attachments.push({fileName: file.name, fileUrl: file.url})
          })
          this.form.isEngineering = 0;
          submit(this.form).then((res) => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.resetForm();
            this.onLoad(this.page);
            console.log(this.fileList);
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    submitAudit() {
      this.$refs['optForm'].validate((valid) => {
        if (valid) {
          this.fileList.forEach(file => {
            this.form.attachments.push({fileName: file.name, fileUrl: file.url})
          })
          this.form.isEngineering = 0;
          this.loading = true;
          submitAudit(this.form).then((res) => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.resetForm();
            this.onLoad(this.page);
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    forward() {
      this.$refs['optForm'].validate((valid) => {
        if (valid) {
          this.fileList.forEach(file => {
            this.form.attachments.push({fileName: file.name, fileUrl: file.url})
          })
          this.loading = true;
          forward(this.form).then((res) => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.resetForm();
            this.onLoad(this.page);
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    sendEvidence() {
      this.$refs['optForm'].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.fileList.forEach(file => {
            this.form.attachments.push({fileName: file.name, fileUrl: file.url})
          })
          this.form.isEngineering = 0;
          sendEvidence(this.form).then((res) => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.resetForm();
            this.onLoad(this.page);
            console.log(this.fileList);
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    /**=========审批相关==begin===========*/
    showTaskAuditTaskDialog(row) {
      this.taskAuditDialog = true;
      this.$refs['taskAuditDialog'].initData({taskId: row.taskId, processId: row.processId});
    },
    closeTaskAuditTaskDialog() {
      this.taskAuditDialog = false;
    },
    setTaskAuditTaskDialog() {
      this.taskAuditDialog = false;
      this.onLoad(this.page);
    },
    showTaskAuditLogDialog(row) {
      this.processId = row.processId;
      this.taskAuditLogDialog = true;
    },
    closeTaskAuditTaskLogDialog() {
      this.taskAuditLogDialog = false;
    },
    /**=========审批相关==end===========*/
    downloadWord: function(row) {
      this.downBlobFile(
        "/exam/auditEvidence/downloadWord/"+ row.evidenceId,
        {},
        row.projectName + "取证单.docx"
      )
    },
    wordFileHandle(e) {
      console.log(e,987987979);
      this.$set(this.form, "wordFile", e.wordFile);
      this.$set(this.form, "evidenceId", e.id);
    },

    showReplyBox(row) {
      getEvidence(row.evidenceId).then((res) => {
        this.form = res.data.data;
        this.fileList = this.form.attachments;
        this.fileList.forEach((item) =>{
          item.name = item.fileName;
        })
        this.replyBox = true;
      });
    },

    showAuditBox(row) {
      getEvidence(row.evidenceId).then((res) => {
        this.form = res.data.data;
        this.fileList = this.form.attachments;
        this.fileList.forEach((item) =>{
          item.name = item.fileName;
        })
        this.auditBox = true;
      });
    },

    showConfirmBox(row) {
      getEvidence(row.evidenceId).then((res) => {
        this.form = res.data.data;
        this.fileList = this.form.attachments;
        this.fileList.forEach((item) =>{
          item.name = item.fileName;
        })
        this.confirmBox = true;
      });
    },

    handleCloseEvidence() {
      this.$refs['optForm'].validate((valid) => {
        if (valid) {
          this.fileList.forEach(file => {
            this.form.attachments.push({fileName: file.name, fileUrl: file.url})
          })
          this.loading = true;
          closeEvidence(this.form).then((res) => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.resetForm();
            this.onLoad(this.page);
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    handleSelectionChange(val){
      this.selectedRows.key = val[0].projectId;
      this.selectedRows.value = val;
    },
    submitApproval(row){
      this.$confirm("如未选择要提交审批的取证单，系统会默认提交该项目下所有未审批的取证单！", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        console.log("提交")
        this.loading = true;
        this.form.projectId = row.projectId;
        if (this.selectedRows.key && this.selectedRows.key === row.projectId){
          this.form.auditEvidences = this.selectedRows.value;
        }
        submitApproval(this.form).then(() => {
          this.loading = false;
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.selectedRows.key = '';
          this.selectedRows.value = [];
          this.onLoad(this.page);
          console.log(this.selectedRows)
        });
      });
    },
    approvalThrough(row){
      this.$confirm("如未选择要审批的取证单，系统会默认通过该项目下所有已提交的取证单！", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        console.log("提交")
        this.loading = true;
        this.form.projectId = row.projectId;
        if (this.selectedRows.key && this.selectedRows.key === row.projectId){
          this.form.auditEvidences = this.selectedRows.value;
        }
        approvalThrough(this.form).then(() => {
          this.loading = false;
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.selectedRows.key = '';
          this.selectedRows.value = [];
          this.onLoad(this.page);
          console.log(this.selectedRows)
        });
      });
    },
    // -- 穿梭框
    showTransferDialog(transferDialogArr, transferDialogType, transferDialogMultiple, transferDialogQuery) {
      this.transferDialogArr = transferDialogArr; // 表单字段
      this.transferDialogType = transferDialogType; // 判断类型user:人员，unit:职位，department:部门,company:单位,plan:计划等
      this.transferDialogMultiple = transferDialogMultiple; // 是否多选
      if (transferDialogType === 'developer') {
        this.transferCurrent.types = transferDialogQuery;
      }
      // if (transferDialogType === 'contacts') {
      //   this.transferCurrent.jobCategory = transferDialogQuery; // jobCategory:3010 中层领导
      // }
      //重组数组name和id
      this.transferCurrent.currentval = []
      if(this.form[transferDialogArr[0]]) {
        if (this.form[transferDialogArr[0]].indexOf(',') > -1) {
          this.form[transferDialogArr[0]].split(',').forEach((item, i) => {
            this.transferCurrent.currentval.push({name: this.form[transferDialogArr[1]].split(',')[i], id: item})
          })
        } else {
          this.transferCurrent.currentval = [{name: this.form[transferDialogArr[1]], id: this.form[transferDialogArr[0]]}]
        }
        console.log(this.form[transferDialogArr[0]])
      }
      this.transferDialog = true;
    },
    closeTransfer() {
      this.transferDialog = false
      this.transferDialogType = ''
    },
    // 已选定数据的更新判断
    transferDataHandle(e) {
      this.transferDialog = false
      let currentval = [], currentLabel = []
      if (e.list.length > 0) {
        if (e.list.length > 1) {
          e.list.forEach(item => {
            currentval.push(item.id)
            currentLabel.push(item.name)
          })
        } else {
          currentval = [e.list[0].id]
          currentLabel = [e.list[0].name]
        }
        this.$set(this.form, this.transferDialogArr[0], currentval.join(','))
        this.$set(this.form, this.transferDialogArr[1], currentLabel.join(','))
      } else { // 如果返回的数据为空，也将当前页面数值清空
        this.$set(this.form, this.transferDialogArr[0], '')
        this.$set(this.form, this.transferDialogArr[1], '')
      }
      this.transferDialogType = ''
    },
    openLawFunction(val) {
      this.TableLawVisible = true;
    },
    closeLawDialog(val) {
      if (val) this.$set(this.form, 'lawContent', val)
      this.TableLawVisible = false;
    }
  }
}
</script>
